﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web.Management;
using System.Collections.Specialized;
using System.Collections;
using System.Web;

namespace KgUtils.HealthMonitoring
{
    public class ErrorWebEvent : WebErrorEvent
    {
        protected StringDictionary details = new StringDictionary();
        public StringDictionary Details
        {
            get { return details; }
            set { details = value; }
        }

        public ErrorWebEvent(Exception exception, object eventSource)
            : base(exception.Message, eventSource, WebEventCodes.WebExtendedBase + 7000, exception)
        {
            AddMoreRequestInformation();
        }

        public ErrorWebEvent(string message, Exception exception, object eventSource)
            : base(message, eventSource, WebEventCodes.WebExtendedBase + 7000, exception)
        {
            AddMoreRequestInformation();
        }

        public ErrorWebEvent(string message, object eventSource)
            : base(message, eventSource, WebEventCodes.WebExtendedBase + 7000, new Exception())
        {
            AddMoreRequestInformation();
        }

        public override void FormatCustomEventDetails(WebEventFormatter formatter)
        {
            base.FormatCustomEventDetails(formatter);
            foreach (DictionaryEntry item in Details)
                formatter.AppendLine(String.Concat(item.Key, " : ", item.Value));
        }

        protected void AddMoreRequestInformation()
        {
            try
            {
                //Log additionnal request informations.
                if (HttpContext.Current != null && HttpContext.Current.Request != null)
                {
                    var request = HttpContext.Current.Request;
                    if (request.UrlReferrer != null)
                        Details.Add("Referrer", request.UrlReferrer.ToString());
                    else
                        Details.Add("Referrer", String.Empty);

                    if (request.HttpMethod != null)
                        Details.Add("HttpMethod", request.HttpMethod);

                    if (request.UserAgent != null)
                        Details.Add("UserAgent", request.UserAgent);
                }
            }
            catch (Exception ex)
            {
                Details.Add("AdditionalInfoError", String.Concat("Error retrieving additional info :", ex.Message));
            }
        }
    }
}
